package com.anuo.app.common.globalhandle;


import com.anuo.app.common.entity.Response;
import com.anuo.app.common.utils.ExceptionUtil;
import com.anuo.app.common.utils.JsonUtil;
import com.anuo.app.common.utils.NetUtil;
import com.anuo.app.common.utils.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 全局异常捕获
 * 遗留问题: 此处能捕获全局的 显式抛出来的异常,但不能捕获 非try catch下, java代码的一些异常, 总的来说不影响常规使用,但能解决这个
 * 问题更好
 * 参考如下链接解决遗留问题: http://www.baeldung.com/global-error-handler-in-a-spring-rest-api
 */
// 参考: http://www.baeldung.com/exception-handling-for-rest-with-spring
@ControllerAdvice
public class GlobalRestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {Exception.class, RuntimeException.class, AppException.class})
    protected ResponseEntity<Object> handleException(WebRequest request, Exception ex, AppException appEx) {
        Response response = new Response();
        response.setSuccess(false);

        if (StringUtils.isNotEmpty(appEx.getMessage())) {
            response.setMessage(appEx.getMessage());
        } else {
            response.setMessage(appEx.getAppMessage());
        }

        response.setErrorCode(appEx.getErrorCode());
        response.setStacktrace(ExceptionUtil.getStackTrace(appEx));
        response.setServerIp(NetUtil.getServerIp())
        ;
        String errorBody = JsonUtil.toJsonPretty(response);

        return handleExceptionInternal(appEx, errorBody,
                new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }


}
